﻿/*----------------------------------------------------------------
// Copyright (C) 2012
// 版权所有
//
// 文件名：StringUtil.cs
// 文件功能描述：
//
//
// 创建标识：Libing 2010-01-28 15:13:17 星期四
//
// 修改标识：
// 修改描述：
//----------------------------------------------------------------*/

using System;
using System.Collections.Generic;
using System.Text;

using System.Web;
using System.Text.RegularExpressions;

public class StringUtil
{
    #region 属性

    /// <summary>
    /// 整数默认值
    /// </summary>
    public static int DefaultValue
    {
        get
        {
            return -1;
        }
    }

    #endregion

    #region 构造函数

    /// <summary>
    /// 默认构造函数
    /// </summary>
    public StringUtil()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }

    #endregion

    #region 时间日期

    /// <summary>
    /// 当前日期字符串
    /// </summary>
    public static string CurrentDateString
    {
        get
        {
            return System.DateTime.Now.ToString("yyyy-MM-dd");
        }
    }

    /// <summary>
    /// 当前日期数字字符串
    /// </summary>
    public static string CurrentDateDigitalString
    {
        get
        {
            return System.DateTime.Now.ToString("yyyyMMdd");
        }
    }

    /// <summary>
    /// 当前时间字符串
    /// </summary>
    public static string CurrentDateTimeString
    {
        get
        {
            return System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); // 时间24小时制
        }
    }

    /// <summary>
    /// 时间字符串 — 将 DateTime 类型时间转化成字符串
    /// </summary>
    /// <param name="dt">时间</param>
    /// <returns></returns>
    public static string DateTimeString(DateTime dt)
    {
        return dt.ToString("yyyy-MM-dd HH:mm:ss");
    }

    /// <summary>
    /// 时间字符串 — 将 DateTime 类型时间转化成字符串
    /// </summary>
    /// <param name="dt">时间</param>
    /// <returns></returns>
    public static string DateTimeString(DateTime? dt)
    {
        if (dt != null)
        {
            return Convert.ToDateTime(dt).ToString("yyyy-MM-dd HH:mm:ss");
        }

        return CurrentDateTimeString;
    }

    /// <summary>
    /// 时间字符串 — 将 object 类型时间转化成字符串
    /// </summary>
    /// <param name="value">时间</param>
    /// <returns></returns>
    public static string DateTimeString(object value)
    {
        try
        {
            return Convert.ToDateTime(value).ToString("yyyy-MM-dd HH:mm:ss");
        }
        catch
        {
            return CurrentDateTimeString;
        }
    }

    /// <summary>
    /// 日期字符串 — 将 DateTime 类型时间转化成字符串
    /// </summary>
    /// <param name="dt">时间</param>
    /// <returns></returns>
    public static string DateString(DateTime dt)
    {
        return dt.ToString("yyyy-MM-dd");
    }

    /// <summary>
    /// 日期字符串 — 将 DateTime 类型时间转化成字符串
    /// </summary>
    /// <param name="dt">时间</param>
    /// <returns></returns>
    public static string DateString(DateTime? dt)
    {
        if (dt != null)
        {
            return Convert.ToDateTime(dt).ToString("yyyy-MM-dd");
        }

        return CurrentDateString;
    }

    /// <summary>
    /// 日期字符串 — 将 object 类型时间转化成字符串
    /// </summary>
    /// <param name="value">时间</param>
    /// <returns></returns>
    public static string DateString(object value)
    {
        try
        {
            return Convert.ToDateTime(value).ToString("yyyy-MM-dd");
        }
        catch
        {
            return CurrentDateString;
        }
    }

    public static string DayString(DateTime dt)
    {
        return dt.ToString("MM-dd");
    }

    public static string DayString(DateTime? dt)
    {
        return Convert.ToDateTime(dt).ToString("MM-dd");
    }

    #endregion

    #region 字符串操作

    /// <summary>
    /// 获取字符串长度 — 双字节字符 2 个单位长度
    /// </summary>
    /// <param name="value">字符串</param>
    /// <returns>长度</returns>
    public static int Length(string value)
    {
        if (String.IsNullOrEmpty(value))
        {
            return 0;
        }

        //int length = 0;
        //foreach (char chr in value)
        //{
        //    if (((int)chr) < 0 || ((int)chr) > 126)
        //    {
        //        length = length + 2;
        //    }
        //    else
        //    {
        //        length = length + 1;
        //    }
        //}

        //return length;

        return Encoding.Default.GetBytes(value).Length;
    }

    /// <summary>
    /// 截取字符串
    /// </summary>
    /// <param name="value">字符串</param>
    /// <param name="length">最多显示的字符长度(双字节字符 2 个单位长度),超出部分使用...代替</param>
    /// <returns></returns>
    public static string SubString(string value, int length)
    {
        int realLength = 0;
        for (int i = 0; i < value.Length; i++)
        {
            //if (value[i] >= 0x4e00 && value[i] <= 0x9fa5)
            //{
            //    realLength += 2;
            //}
            //else
            //{
            //    realLength++;
            //}

            realLength += Encoding.Default.GetBytes(value[i].ToString()).Length;

            if (realLength == length)
            {
                return value.Substring(0, i + 1) + "...";
            }
            else if (realLength > length)
            {
                return value.Substring(0, i) + "...";
            }
        }

        return value;
    }

    /// <summary>
    /// 截取字符串
    /// </summary>
    /// <param name="value">字符串</param>
    /// <param name="length">最多显示的字符长度(双字节字符 2 个单位长度),超出部分不显示</param>
    /// <returns></returns>
    public static string SubStringIgnore(string value, int length)
    {
        int realLength = 0;
        for (int i = 0; i < value.Length; i++)
        {
            //if (value[i] >= 0x4e00 && value[i] <= 0x9fa5)
            //{
            //    realLength += 2;
            //}
            //else
            //{
            //    realLength++;
            //}

            realLength += Encoding.Default.GetBytes(value[i].ToString()).Length;

            if (realLength == length)
            {
                return value.Substring(0, i + 1);
            }
            else if (realLength > length)
            {
                return value.Substring(0, i);
            }
        }

        return value;
    }

    /// <summary>
    /// 检测网址
    /// </summary>
    /// <param name="url">网址</param>
    /// <returns>网址格式字符串</returns>
    public static string FormatUrl(string url)
    {
        //string[] UserHost = url.Split(new Char[] { ':' });  //数组，以“.”分隔
        //string str = UserHost[0].ToString();

        string str = url.Split(new char[] { ':' })[0].ToString();

        if (str.ToLower().Equals("http"))
        {
            return url;
        }
        else
        {
            return "http://" + url;
        }
    }

    /// <summary>
    /// 根据真实 ipAddress 把最后ip地址变成*
    /// </summary>
    /// <param name="ipAddress">ip地址</param>
    /// <returns></returns>
    public static string FormatIPAddress(string ipAddress)
    {
        if (String.IsNullOrEmpty(ipAddress) || ipAddress.LastIndexOf(".") == -1)
        {
            return "127.0.0.*";
        }

        return ipAddress.Substring(0, ipAddress.LastIndexOf(".")) + ".*";
    }

    /// <summary>
    /// 空字符串替换html格式
    /// </summary>
    /// <param name="value">字符串</param>
    /// <returns></returns>
    public static string FormatEmpty(string value)
    {
        if (String.IsNullOrEmpty(value))
        {
            return "&nbsp;";
        }

        return value;
    }

    #endregion

    #region Html 标记

    /// <summary>
    /// 过滤Html标记
    /// </summary>
    /// <param name="value">内容</param>
    /// <returns></returns>
    public static string RemoveHtml(string value)
    {
        //删除脚本
        value = Regex.Replace(value, @"<[^>]*?>.*?</>", "", RegexOptions.IgnoreCase);

        //删除表格HTML
        value = Regex.Replace(value, @"<?xml[^>]*>", "", RegexOptions.IgnoreCase);
        value = value.Replace("<?", "");
        value = Regex.Replace(value, @"</?table[^>]*>", "", RegexOptions.IgnoreCase);
        value = Regex.Replace(value, @"</?o:p[^>]*>", "", RegexOptions.IgnoreCase);
        value = Regex.Replace(value, @"</?p[^>]*>", "", RegexOptions.IgnoreCase);
        value = Regex.Replace(value, @"</?font[^>]*>", "", RegexOptions.IgnoreCase);
        value = Regex.Replace(value, @"</?div[^>]*>", "", RegexOptions.IgnoreCase);
        value = Regex.Replace(value, @"</?span[^>]*>", "", RegexOptions.IgnoreCase);
        value = Regex.Replace(value, @"</?b style[^>]*>", "", RegexOptions.IgnoreCase);
        value = Regex.Replace(value, @"</?tr[^>]*>", "", RegexOptions.IgnoreCase);
        value = Regex.Replace(value, @"</?td[^>]*>", "", RegexOptions.IgnoreCase);
        value = Regex.Replace(value, @"</?th[^>]*>", "", RegexOptions.IgnoreCase);
        value = Regex.Replace(value, @"</?blockquote[^>]*>", "", RegexOptions.IgnoreCase);
        value = Regex.Replace(value, @"</?tbody[^>]*>", "", RegexOptions.IgnoreCase);
        value = Regex.Replace(value, @"<style[^\s]*", "", RegexOptions.IgnoreCase);

        value = value.Replace("&nbsp;", "");

        return value;
    }

    /// <summary>
    /// 获取指定长度的内容简介
    /// </summary>
    /// <param name="value">内容</param>
    /// <param name="length">指定获取长度</param>
    /// <returns></returns>
    public static string RemoveHtmlSubString(string value, int length)
    {
        return SubString(RemoveHtml(value), length);
    }

    /// <summary>
    /// 过滤Html标记
    /// </summary>
    /// <param name="value">内容</param>
    /// <returns></returns>
    public static string ClearHtml(string value)
    {
        if (String.IsNullOrEmpty(value))
        {
            return String.Empty;
        }

        value = Regex.Replace(value, "<[^>]*>", "");

        return value.Replace("&nbsp;", "");
    }

    /// <summary>
    /// 获取指定长度的内容简介
    /// </summary>
    /// <param name="value">内容</param>
    /// <param name="length">指定获取长度</param>
    /// <returns></returns>
    public static string ClearHtmlSubString(string value, int length)
    {
        return SubString(ClearHtml(value), length);
    }

    /// <summary>
    /// Converts plain text to HTML
    /// </summary>
    /// <param name="Text">Text</param>
    /// <returns>Formatted text</returns>
    public static string ConvertPlainTextToHtml(string Text)
    {
        if (String.IsNullOrEmpty(Text))
        {
            return String.Empty;
        }

        Text = Text.Replace("\r\n", "<br />");
        Text = Text.Replace("\r", "<br />");
        Text = Text.Replace("\n", "<br />");
        Text = Text.Replace("\t", "&nbsp;&nbsp;");
        Text = Text.Replace("  ", "&nbsp;&nbsp;");

        return Text;
    }

    /// <summary>
    /// Converts HTML to plain text
    /// </summary>
    /// <param name="Text">Text</param>
    /// <returns>Formatted text</returns>
    public static string ConvertHtmlToPlainText(string Text)
    {
        if (String.IsNullOrEmpty(Text))
        {
            return String.Empty;
        }

        Text = Text.Replace("<br>", "\n");
        Text = Text.Replace("<br >", "\n");
        Text = Text.Replace("<br />", "\n");
        Text = Text.Replace("&nbsp;&nbsp;", "\t");
        Text = Text.Replace("&nbsp;&nbsp;", "  ");

        return Text;
    }

    #endregion

    #region 数据类型转化

    /// <summary>
    /// Boolean 类型转化
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static bool ConvertToBoolean(object value)
    {
        return value.ToString().Equals("1") || value.ToString().ToLower().Equals("true");
    }

    /// <summary>
    /// Byte 类型转化
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static byte ConvertToByte(object value)
    {
        try
        {
            return Convert.ToByte(value);
        }
        catch
        {
            return (byte)DefaultValue;
        }
    }

    /// <summary>
    /// Byte 类型转化
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static byte ConvertToByte(bool value)
    {
        if (value)
        {
            return 1;
        }

        return 0;
    }

    /// <summary>
    /// Int32 类型转化
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static int ConvertToInt32(object value)
    {
        try
        {
            if (value == null)
            {
                return DefaultValue;
            }

            return Convert.ToInt32(value);
        }
        catch
        {
            return DefaultValue;
        }
    }

    /// <summary>
    /// Int32 类型转化
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static int ConvertToInt32(bool value)
    {
        if (value)
        {
            return 1;
        }

        return 0;
    }

    /// <summary>
    /// Int32 类型转化
    /// </summary>
    /// <param name="value"></param>
    /// <param name="_defaultValue">转化失败时默认值</param>
    /// <returns></returns>
    public static int ConvertToInt32(string value, int _defaultValue)
    {
        try
        {
            return Convert.ToInt32(value);
        }
        catch
        {
            return _defaultValue;
        }
    }

    /// <summary>
    /// Decimal 类型转化
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static decimal ConvertToDecimal(string value)
    {
        try
        {
            return Convert.ToDecimal(value);
        }
        catch
        {
            return 0m;
        }
    }

    /// <summary>
    /// Decimal 类型转化
    /// </summary>
    /// <param name="value"></param>
    /// <param name="_defaultValue">转化失败时默认值</param>
    /// <returns></returns>
    public static decimal ConvertToDecimal(string value, decimal _defaultValue)
    {
        try
        {
            return Convert.ToDecimal(value);
        }
        catch
        {
            return _defaultValue;
        }
    }

    /// <summary>
    /// DateTime 类型转化
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static System.DateTime ConvertToDateTime(string value)
    {
        try
        {
            if (String.IsNullOrEmpty(value))
            {
                return System.DateTime.Now;
            }

            return Convert.ToDateTime(value);
        }
        catch
        {
            return System.DateTime.Now;
        }
    }

    /// <summary>
    /// DateTime 类型转化
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static System.DateTime? ConvertToDateTimeNullable(string value)
    {
        try
        {
            if (String.IsNullOrEmpty(value))
            {
                return null;
            }

            return Convert.ToDateTime(value);
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// 字符串类型转化
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string ConvertToString(string value)
    {
        try
        {
            if (String.IsNullOrEmpty(value))
            {
                return String.Empty;
            }

            return Convert.ToString(value);
        }
        catch
        {
            return null;
        }
    }

    #endregion

    #region HTTP 查询字符串变量

    /// <summary>
    /// String 类型变量
    /// </summary>
    /// <param name="name">变量名</param>
    /// <returns></returns>
    public static string QueryString(string name)
    {
        string result = String.Empty;

        if (HttpContext.Current != null
            && HttpContext.Current.Request.QueryString[name] != null)
        {
            result = HttpContext.Current.Request.QueryString[name].ToString();
        }

        return result;
    }

    /// <summary>
    /// Boolean 类型变量
    /// </summary>
    /// <param name="name">变量名</param>
    /// <returns></returns>
    public static bool QueryStringToBoolean(string name)
    {
        string result = QueryString(name).ToUpperInvariant();
        return (result.Equals("YES") || result.Equals("TRUE") || result.Equals("1"));
    }

    /// <summary>
    /// Boolean 类型变量
    /// </summary>
    /// <param name="name">变量名</param>
    /// <returns></returns>
    public static bool? QueryStringToBooleanNullable(string name)
    {
        string result = QueryString(name).ToUpperInvariant();

        if (result.Length > 0)
        {
            if (!result.Equals("-1"))
            {
                return (result.Equals("YES") || result.Equals("TRUE") || result.Equals("1"));
            }
        }

        return null;
    }

    /// <summary>
    /// Int32 类型变量
    /// </summary>
    /// <param name="name">变量名</param>
    /// <returns></returns>
    public static int QueryStringToInt32(string name)
    {
        string result = QueryString(name).ToUpperInvariant();

        if (result.Length > 0)
        {
            try
            {
                return Convert.ToInt32(result);
            }
            catch
            {
                return DefaultValue;
            }
        }

        return DefaultValue;
    }

    /// <summary>
    /// Int32 类型变量
    /// </summary>
    /// <param name="name">变量名</param>
    /// <param name="_defaultValue">转化失败时的默认值</param>
    /// <returns></returns>
    public static int QueryStringToInt32(string name, int _defaultValue)
    {
        string result = QueryString(name).ToUpperInvariant();

        if (result.Length > 0)
        {
            try
            {
                return Convert.ToInt32(result);
            }
            catch
            {
                return _defaultValue;
            }
        }

        return _defaultValue;
    }

    /// <summary>
    /// DateTime 类型变量
    /// </summary>
    /// <param name="name">变量名</param>
    /// <returns></returns>
    public static DateTime QueryStringToDateTime(string name)
    {
        string result = QueryString(name).ToUpperInvariant();

        if (result.Length > 0)
        {
            try
            {
                return Convert.ToDateTime(result);
            }
            catch
            {
                return System.DateTime.Now;
            }
        }

        return System.DateTime.Now;
    }

    /// <summary>
    /// DateTime? 类型变量
    /// </summary>
    /// <param name="name">变量名</param>
    /// <returns></returns>
    public static DateTime? QueryStringToDateTimeNullable(string name)
    {
        string result = QueryString(name).ToUpperInvariant();

        if (result.Length > 0)
        {
            try
            {
                return Convert.ToDateTime(result);
            }
            catch
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    }

    /// <summary>
    /// Decimal? 类型变量
    /// </summary>
    /// <param name="name">变量名</param>
    /// <returns></returns>
    public static Decimal? QueryStringToDecimalNullable(string name)
    {
        string result = QueryString(name).ToUpperInvariant();

        if (result.Length > 0)
        {
            try
            {
                return Convert.ToDecimal(result);
            }
            catch
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    }

    public static string QueryStringToGuid(string name)
    {
        string result = QueryString(name).ToUpperInvariant();

        if (result.Length == 36)
        {
            return result;
        }

        return Guid.NewGuid().ToString();
    }

    #endregion

    #region 数据库设计字段格式化

    /// <summary>
    /// 性别
    /// </summary>
    /// <param name="sex"></param>
    /// <returns></returns>
    public static string FormatSex(object sex)
    {
        switch (Convert.ToBoolean(sex))
        {
            case false:
                return "女";

            case true:
                return "男";

            default:
                return String.Empty;
        }
    }

    /// <summary>
    /// 格式化图片大小
    /// </summary>
    /// <param name="width">宽度</param>
    /// <param name="height">高度</param>
    /// <returns></returns>
    public static string FormatSize(object width, object height)
    {
        return String.Format("{0}*{1} px", width, height);
    }

    /// <summary>
    /// 格化数字，清除小数点后的0
    /// </summary>
    /// <param name="value">数字</param>
    /// <returns></returns>
    public static string FormatDigital(object value)
    {
        return value.ToString().Replace(".0", String.Empty);
    }

    /// <summary>
    /// 格式化启用状态
    /// </summary>
    /// <param name="isValid"></param>
    /// <returns></returns>
    public static string FormatIsValid(object isValid)
    {
        return String.Format("<span style='color:{0};'>{1}</span>", ConvertToBoolean(isValid) ? "Green" : "Red", ConvertToBoolean(isValid) ? "启用" : "禁用");
    }

    #endregion

    #region 树形菜单

    /// <summary>
    /// 树形菜单前缀
    /// </summary>
    /// <param name="depth"></param>
    /// <returns></returns>
    public static string GetTreePrefix(string nodeName, int depth)
    {
        StringBuilder prefix = new StringBuilder();

        if (depth == 0)
        {
            return String.Empty;
        }

        for (int i = 1; i <= depth; i++)
        {
            prefix.Append("　");
        }

        return String.Format("{0} |- {1}", prefix.ToString(), nodeName);
    }

    #endregion

    #region 广告

    /// <summary>
    /// 广告内容缩略
    /// </summary>
    /// <param name="typeID"></param>
    /// <param name="adContent"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <returns></returns>
    public static string GetADContentThumbnail(object typeID, object adContent, int width, int height)
    {
        switch (Convert.ToUInt32(typeID))
        {
            case 1:
                return String.Format("<div><object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0' width='{0}' height='{1}'> <param name='movie' value='{2}' /> <param name='quality' value='high' /> <embed src='{2}' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='{0}' height='{1}'></embed> </object></div>", width, height, adContent);

            case 2:
                return String.Format("<img width='{0}px' src='{1}'>", width, adContent);

            default:
                return adContent.ToString();
        }
    }

    public static string GetADFlashLine(int width, int height, string adContent)
    {
        return String.Format("<div><object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0' width='{0}' height='{1}'> <param name='movie' value='{2}' /> <param name='quality' value='high' /> <embed src='{2}' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='{0}' height='{1}'></embed> </object></div>", width, height, adContent);
    }

    public static string GetADPictureLine(int width, int height, string adContent)
    {
        return String.Format("<div><img width='{0}' height='{1}' src='{2}'/></div>", width, height, adContent);
    }

    public static string FormatADContent(int typeID, string link, int width, int height, string url)
    {
        switch (typeID)
        {
            case 1:
                return String.Format("<a target='_blank' href='{3}'><object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0' width='{0}' height='{1}'> <param name='movie' value='{2}' /> <param name='quality' value='high' /> <embed src='{2}' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='{0}' height='{1}'></embed> </object></a>", width, height, url, link);

            default:
                return String.Format("<a target='_blank' href='{0}'><img width='{1}' height='{2}' src='{3}'/></a>", link, width, height, url);
        }
    }

    #endregion

}
